#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2015-01-08 09:00:19
# @Author  : Your Name (Netxy@vip.qq.com)
# @Link    : http://www.itspas.com
# @Version : $Id$

import os
import sys
import json
# import urllib2
import shutil
import platform

G_HOST_DEFAULT_URL = 'https://raw.githubusercontent.com/racaljk/hosts/master/hosts'
G_INIT_DEFAULT_SHELL = 'bash'


class utils:

    @staticmethod
    def is_windows():
        return platform.system() == 'Windows'

    @staticmethod
    def is_darwin():
        return platform.system() == 'Darwin'

    @staticmethod
    def get_dir_usr(file):
        return '%s/%s' % (os.path.expanduser('~'), file)

    @staticmethod
    def get_dir_file(file):
        evn_path = os.path.abspath(os.path.dirname(__file__))
        return '%s/%s' % (evn_path if len(evn_path) > 0 else '.', file)

    @staticmethod
    def get_json():
        json_json = {'default': {'PATH': []}}
        path_json = utils.get_dir_file('data.data')
        if not os.path.exists(path_json):
            return json_json
        file_json = open(path_json)
        content = file_json.read()
        file_json.close()
        return json_json if len(content) == 0 else json.loads(content)

    @staticmethod
    def update_json(json_json):
        path_json = utils.get_dir_file('data.data')
        if not os.path.exists(os.path.dirname(path_json)):
            os.makedirs(os.path.dirname(path_json))
        content = json.dumps(json_json)
        if len(content) > 0:
            file_json = open(path_json, 'wb')
            file_json.write(content)
            file_json.close()
            if utils.is_windows():
                file_bat = open(utils.get_dir_file('AutoPath.bat'), 'wb')
                file_bat.write('@ECHO OFF\n')
                for k in json_json['default']:
                    if k == 'PATH':
                        for v in json_json['default'][k]:
                            file_bat.write('SET PATH=%sPATH%s;%s;\n' % ('%', '%', v))
                    else:
                        file_bat.write('SET %s=%s\n' % (k, json_json['default'][k]))
                file_bat.close()
            elif utils.is_darwin():
                file_sh = open(utils.get_dir_file('.profile'), 'wb')
                for k in json_json['default']:
                    if k == 'PATH':
                        for v in json_json['default'][k]:
                            file_sh.write('PATH=$PATH:%s\n' % v.replace(' ', '\ '))
                        file_sh.write('export PATH\n')
                    elif k == 'ALIAS':
                        for v in json_json['default'][k]:
                            file_sh.write('alias %s="%s"\n' % (v, json_json['default'][k][v]))
                    else:
                        file_sh.write('%s=%s\n' % (k, json_json['default'][k].replace(' ', '\ ')))
                        file_sh.write('export %s' % (k))
                file_sh.close()

    @staticmethod
    def help():
        print('Use:')
        print('\tevn init %s' % '[bash|zsh]' if utils.is_darwin() else '')
        print('\tevn add [name] path')
        print('\tevn del key')
        print('\tevn cfg name [save|remove]')
        print('\tevn view')
        print('\tevn host')
        if utils.is_darwin():
            print('\tevn alias name [value]')

    @staticmethod
    def handle_add():
        key = 'PATH' if len(sys.argv) < 4 else sys.argv[2]
        value = sys.argv[2 if key == 'PATH' else 3] if len(sys.argv) > 2 else None
        if value:
            json_json = utils.get_json()
            if key == 'PATH':
                value = os.path.abspath(os.getcwd()) if value == '.' else value
                if value not in json_json['default'][key]:
                    json_json['default'][key].append(value)
            else:
                json_json['default'][key] = os.path.abspath(value)
            utils.update_json(json_json)

    @staticmethod
    def handle_del():
        value = sys.argv[2] if len(sys.argv) > 2 else None
        if value:
            json_json = utils.get_json()
            if value.isdigit() and len(json_json['default']['PATH']) > int(value):
                json_json['default']['PATH'].pop(int(value))
            elif value in json_json['default'].keys():
                json_json['default'].pop(value)
            utils.update_json(json_json)

    @staticmethod
    def handle_cfg():
        value = sys.argv[2] if len(sys.argv) > 2 else None
        if value:
            json_json = utils.get_json()
            if 'remove' in sys.argv and value in json_json:
                json_json.pop(value)
            elif 'save' in sys.argv:
                json_json[value] = json_json['default']
            elif value in json_json:
                json_json['default'] = json_json[value]
            utils.update_json(json_json)

    @staticmethod
    def handle_view():
        json_json = utils.get_json()
        for cfg in json_json.keys():
            print('%s' % cfg)
            for i in range(len(json_json[cfg]['PATH'])):
                print('\t%i:%s' % (i, json_json[cfg]['PATH'][i]))
            for key in json_json[cfg]:
                if key in ('PATH', 'ALIAS'):
                    continue
                print('\t%s:%s' % (key, json_json[cfg][key]))
            if utils.is_darwin and 'ALIAS' in json_json[cfg] and len(json_json[cfg]['ALIAS']) > 0:
                print('\talias:')
                for k in json_json[cfg]['ALIAS']:
                    print('\t\t%s="%s"' % (k, json_json[cfg]['ALIAS'][k]))

    @staticmethod
    def handle_init():
        if utils.is_windows():
            import _winreg
            key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\Microsoft\Command Processor', 0, _winreg.KEY_ALL_ACCESS)
            _winreg.SetValueEx(key, 'AutoRun', 0, _winreg.REG_SZ, os.path.abspath(os.path.dirname(__file__) + '/AutoPath.bat'))
            _winreg.FlushKey(key)
            _winreg.CloseKey(key)
        elif utils.is_darwin():
            value = sys.argv[2] if len(sys.argv) > 2 else G_INIT_DEFAULT_SHELL
            path_shell = ''
            if value == 'bash':
                path_shell = utils.get_dir_usr('.profile')
                if not os.path.exists(path_shell):
                    open(path_shell, 'wb').close()
            elif value == 'zsh':
                path_shell = utils.get_dir_usr('.zshrc')
                path_shell = path_shell if os.path.exists(path_shell) else ''
            if len(path_shell) > 0:
                file_shell = open(path_shell, 'rt')
                if 'source %s' % utils.get_dir_file('.profile') not in file_shell.read():
                    file_shell.close()
                    file_shell = open(path_shell, 'a')
                    file_shell.write('source %s\n' % utils.get_dir_file('.profile'))
                    file_shell.close()
                else:
                    file_shell.close()
        print('init successful!')

    @staticmethod
    def handle_host():
        value = sys.argv[2] if len(sys.argv) > 2 else G_HOST_DEFAULT_URL
        request = None
        pyv = platform.python_version()
        if pyv[0] == '2':
            request = __import__('urllib2').urlopen(value)
        elif pyv[0] == '3':
            request = __import__('urllib.request').request.urlopen(value)
        if utils.is_windows():
            host_path = '%s/system32/drivers/etc/hosts' % os.environ['windir']
        elif utils.is_darwin():
            host_path = '/private/etc/hosts'
        shutil.copyfile(host_path, host_path + '.backup')
        file = open(host_path, 'wb')
        file.write(request.read())
        file.close()
        print('hosts content update from %s' % value)

    @staticmethod
    def handle_alias():
        key = 'ALIAS'
        name = sys.argv[2] if len(sys.argv) > 2 else None
        value = ' '.join(sys.argv[3:]) if len(sys.argv) > 3 else None
        json_json = utils.get_json()
        if key not in json_json['default']:
            json_json['default'][key] = {}
        if value:
            json_json['default'][key][name] = value
        elif name in json_json['default'][key]:
            del json_json['default'][key][name]
        utils.update_json(json_json)


if __name__ == "__main__":
    if len(sys.argv) <= 1 or sys.argv[1] == '-help':
        utils.help()
    else:
        if hasattr(utils, 'handle_%s' % sys.argv[1]):
            getattr(utils, 'handle_%s' % sys.argv[1])()
